from PyQt5.QtCore import Qt, QObject, pyqtSignal, pyqtSlot
from RBK.Model.Functions import addRow, addColumn, removeRow, removeColumn, isCore

class Field(QObject):
    errored = pyqtSignal(str)

    def __init__(self, db):
        super().__init__()
        self.db = db
        self.models = self.db.models

    @pyqtSlot(str, str)
    def addField(self, datatype, newfield):
        smodel = self.models['Struct {0}'.format(datatype)]
        dmodel = self.models['Data {0}'.format(datatype)]

        # If this is a core rulebook, add to structure.  Otherwise, skip this
        #   section of code, as this already exists in core rulebook.
        if isCore(self.db.db):
            result = addRow(self.db, smodel, newfield)
            if not result:
                message = 'Unable to add new field {0} into DataType {1}: {2}'.format(newfield, datatype, smodel.lastError().text())
                print(message)
                self.errored.emit(message)
            else:
                row = smodel.match(smodel.index(0, 0), Qt.DisplayRole, newfield)[0].row()
                typeindex = smodel.index(row, 1)
                result = smodel.setData(typeindex, 'Text')

                if not result:
                    message = 'Unable to set "Text" for new row {0}'.format(newfield)
                    self.errored.emit(message)
                else:
                    smodel.dataChanged.emit(typeindex, typeindex)
                    smodel.submitAll()

        #Add column to data table regardless of whether or not core rulebook...
        addColumn(self.db, dmodel, newfield)
        smodel.select()

    @pyqtSlot(str, str)
    def removeField(self, datatype, fieldrow):
        smodel = self.models['Struct {0}'.format(datatype)]
        dmodel = self.models['Data {0}'.format(datatype)]
        removeRow(self.db, smodel, fieldrow)
        removeColumn(self.db, dmodel, fieldrow)

